﻿using MediatR;
using Medical.Api.Write.Application.Command.RecyclingCleaning;
using Medical.Domain.Enum;
using Medical.Domain.RecoveryCleaning;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Write.Application.Handler.RecyclingCleaning
{
    /// <summary>
    /// 撤销登记回收
    /// </summary>修改状态的命令
    public class CancelRecoveryStatusCommandHandlter : IRequestHandler<CancelRecoveryStatusCommand, ApiResult<int>>
    {


        /// <summary>
        /// 登记回收仓储
        /// </summary>
        private readonly IBaseRepository<InstrumentRecovery> instrumentRecoveryRep;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="instrumentRecoveryRep">登记回收仓储</param>
        public CancelRecoveryStatusCommandHandlter(IBaseRepository<InstrumentRecovery> instrumentRecoveryRep)
        {
            this.instrumentRecoveryRep = instrumentRecoveryRep;
        }

        public async Task<ApiResult<int>> Handle(CancelRecoveryStatusCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据ID查找登记回收记录
                var recoveryItem = instrumentRecoveryRep.GetAll().FirstOrDefault(x => x.Id == request.Id);

                if (recoveryItem == null)
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Fail,
                        Data = 0,
                        Msg = "未找到指定的回收登记记录"
                    };

                }

                // 更新回收状态为已回收
                recoveryItem.Status = RecoveryStatusEnum.待回收;
                recoveryItem.RecoveryTime = DateTime.Now;
                // 保存更改
                instrumentRecoveryRep.Update(recoveryItem);

                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Data = 1,
                    Msg = "撤销成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Data = 0,
                    Msg = ex.Message

                };

            }
        }
    }
}
